import React, { useState, useEffect } from 'react';
import { Bug, GitBranch, FileText, Calendar, User, Hash, Database, AlertCircle, CheckCircle, Download } from 'lucide-react';
import { ProjectConfig, GitCommit } from '../types';
import { BrowserGitService, GitChange } from '../services/BrowserGitService';
import { LocalStorageService } from '../services/LocalStorageService';

interface GitDebuggerProps {
  onMessage: (type: 'success' | 'error' | 'info', text: string) => void;
}

export const GitDebugger: React.FC<GitDebuggerProps> = ({ onMessage }) => {
  const [selectedProject, setSelectedProject] = useState<ProjectConfig | null>(null);
  const [gitData, setGitData] = useState<GitChange[] | null>(null);
  const [loading, setLoading] = useState(false);
  const [gitService] = useState(() => new BrowserGitService());

  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [allCommits, setAllCommits] = useState<GitCommit[] | null>(null);
  const [gitStatus, setGitStatus] = useState<{
    isRepoValid: boolean;
    repoPath: string;
    errorMessage?: string;
    rawLogContent?: string;
    totalCommits?: number;
  } | null>(null);
  const [showAllCommits, setShowAllCommits] = useState(false);
  const [commitFilter, setCommitFilter] = useState('');
  const [authorFilter, setAuthorFilter] = useState('');
  const localStorageService = new LocalStorageService();




  // 设置默认日期范围
  useEffect(() => {
    // 设置默认日期范围（最近7天）
    const today = new Date();
    const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
    
    setEndDate(today.toISOString().split('T')[0]);
    setStartDate(sevenDaysAgo.toISOString().split('T')[0]);
  }, []);



  const selectGitRepository = async () => {
    try {
      onMessage('success', '正在选择Git仓库...');
      const result = await gitService.selectGitRepository();
      
      if (result.success) {
        onMessage('success', `成功选择Git仓库: ${result.data}`);
        // 创建一个临时项目配置用于显示
        const tempProject = {
          id: 'selected-repo',
          name: result.data || 'Selected Repository',
          path: result.data || '',
          addedAt: new Date().toISOString()
        };
        setSelectedProject(tempProject);
      } else {
        onMessage('error', result.error || '选择Git仓库失败');
      }
    } catch (error: any) {
      onMessage('error', `选择Git仓库失败: ${error.message}`);
    }
  };

  const analyzeGitData = async () => {
    if (!selectedProject) {
      onMessage('error', '请先选择Git仓库');
      return;
    }

    if (!startDate || !endDate) {
      onMessage('error', '请设置开始和结束日期');
      return;
    }

    setLoading(true);
    setGitData(null);

    try {
      onMessage('success', '正在分析Git数据...');
      
      // 分析Git变更（使用新的本地文件访问方式）
      const changes = await gitService.analyzeChanges(
        startDate,
        endDate,
        [] // 暂时不使用排除模式
      );

      setGitData(changes);
      onMessage('success', `成功获取到 ${changes.length} 条Git变更记录`);
    } catch (error: any) {
      onMessage('error', `Git数据分析失败: ${error.message}`);
      console.error('Git分析错误:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadAllCommits = async () => {
    if (!selectedProject) {
      onMessage('error', '请先选择一个项目');
      return;
    }

    setLoading(true);
    setAllCommits(null);
    setGitStatus(null);

    try {
      onMessage('info', '正在读取所有Git提交记录...');
      
      // 设置项目路径
      await gitService.setProjectPath(selectedProject.path);
      
      // 验证Git仓库
      const isValid = await gitService.verifyGitRepository();
      
      if (!isValid) {
        setGitStatus({
          isRepoValid: false,
          repoPath: selectedProject.path,
          errorMessage: 'Git仓库验证失败，请确保项目包含.git目录'
        });
        onMessage('error', 'Git仓库验证失败');
        return;
      }

      // 读取Git日志文件
      const rawLogContent = await gitService.readGitLogFile();
      
      // 解析提交记录
      const commits = gitService.parseGitLog(rawLogContent);
      
      setAllCommits(commits);
      setGitStatus({
        isRepoValid: true,
        repoPath: selectedProject.path,
        rawLogContent: rawLogContent,
        totalCommits: commits.length
      });
      
      onMessage('success', `成功读取到 ${commits.length} 条Git提交记录`);
    } catch (error: any) {
      setGitStatus({
        isRepoValid: false,
        repoPath: selectedProject?.path || '',
        errorMessage: error.message
      });
      onMessage('error', `读取Git提交记录失败: ${error.message}`);
      console.error('Git提交记录读取错误:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (date: string | Date) => {
    if (!date) return '未知时间';
    const dateObj = typeof date === 'string' ? new Date(date) : date;
    return dateObj.toLocaleString('zh-CN');
  };

  const filteredCommits = allCommits?.filter(commit => {
    const matchesCommitFilter = !commitFilter || 
      commit.message.toLowerCase().includes(commitFilter.toLowerCase()) ||
      commit.hash.toLowerCase().includes(commitFilter.toLowerCase());
    
    const matchesAuthorFilter = !authorFilter || 
      commit.author.toLowerCase().includes(authorFilter.toLowerCase());
    
    return matchesCommitFilter && matchesAuthorFilter;
  }) || [];

  const exportDebugData = () => {
    const debugData = {
      gitStatus,
      allCommits,
      filteredCommits,
      selectedProject,
      timestamp: new Date().toISOString()
    };
    
    const dataStr = JSON.stringify(debugData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `git-debug-data-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    onMessage('success', '调试数据已导出');
  };

  const getUniqueAuthors = () => {
    if (!allCommits) return [];
    const authors = [...new Set(allCommits.map(commit => commit.author))];
    return authors.sort();
  };

  return (
    <div className="space-y-6">
      {/* 调试控制面板 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
        <div className="flex items-center mb-4">
          <Bug className="h-4 w-4 text-orange-600 mr-2" />
          <h2 className="text-lg font-semibold text-gray-900">Git数据调试器</h2>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4">
          {/* Git仓库选择 */}
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">
              Git仓库
            </label>
            <button
              onClick={selectGitRepository}
              className="w-full px-2 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent text-left text-sm"
            >
              {selectedProject ? selectedProject.name : '点击选择Git仓库目录'}
            </button>
          </div>

          {/* 开始日期 */}
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">
              开始日期
            </label>
            <input
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
              className="w-full px-2 py-1.5 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent text-sm"
            />
          </div>

          {/* 结束日期 */}
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">
              结束日期
            </label>
            <input
              type="date"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
              className="w-full px-2 py-1.5 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent text-sm"
            />
          </div>
        </div>

        {/* 当前选中Git仓库信息 */}
        {selectedProject && (
          <div className="bg-green-50 border border-green-200 rounded-md p-3 mb-3">
            <h3 className="text-xs font-medium text-green-800 mb-1">当前Git仓库</h3>
            <div className="text-xs text-green-700">
              <p><strong>仓库名称:</strong> {selectedProject.name}</p>
              <p><strong>选择时间:</strong> {formatDate(selectedProject.addedAt)}</p>
              <p className="text-green-600 mt-1">✓ 已通过Git仓库验证，可以进行数据分析</p>
            </div>
          </div>
        )}

        {/* 操作按钮 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <button
            onClick={analyzeGitData}
            disabled={loading || !selectedProject}
            className="flex items-center justify-center px-6 py-4 bg-gradient-to-r from-warning-600 to-warning-700 text-white rounded-2xl hover:from-warning-700 hover:to-warning-800 focus:outline-none focus:ring-2 focus:ring-warning-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300 font-semibold shadow-strong hover:shadow-stronger transform hover:scale-105"
          >
            {loading ? (
              <>
                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-3"></div>
                <span className="text-lg">分析中...</span>
              </>
            ) : (
              <>
                <GitBranch className="h-5 w-5 mr-3" />
                <span className="text-lg">分析Git数据</span>
              </>
            )}
          </button>
          
          <button
            onClick={loadAllCommits}
            disabled={loading || !selectedProject}
            className="flex items-center justify-center px-6 py-4 bg-gradient-to-r from-info-600 to-info-700 text-white rounded-2xl hover:from-info-700 hover:to-info-800 focus:outline-none focus:ring-2 focus:ring-info-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300 font-semibold shadow-strong hover:shadow-stronger transform hover:scale-105"
          >
            <Database className="h-5 w-5 mr-3" />
            <span className="text-lg">读取所有提交记录</span>
          </button>
          
          <button
            onClick={() => setShowAllCommits(!showAllCommits)}
            disabled={!allCommits}
            className="flex items-center justify-center px-6 py-4 bg-gradient-to-r from-success-600 to-success-700 text-white rounded-2xl hover:from-success-700 hover:to-success-800 focus:outline-none focus:ring-2 focus:ring-success-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300 font-semibold shadow-strong hover:shadow-stronger transform hover:scale-105"
          >
            <FileText className="h-5 w-5 mr-3" />
            <span className="text-lg">{showAllCommits ? '隐藏' : '显示'}提交列表</span>
          </button>
        </div>
        
        {/* 操作按钮状态提示 */}
        {!selectedProject && (
          <p className="text-xs text-gray-500 text-center">请先选择一个项目</p>
        )}
      </div>

      {/* Git数据显示 */}
      {gitData && (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="flex items-center mb-4">
            <FileText className="h-5 w-5 text-green-600 mr-2" />
            <h3 className="text-lg font-semibold text-gray-900">
              Git变更记录 ({gitData.length} 条)
            </h3>
          </div>

          {gitData.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              <FileText className="h-12 w-12 text-gray-300 mx-auto mb-4" />
              <p>在指定时间范围内未找到Git变更记录</p>
              <p className="text-sm mt-2">请检查项目路径是否正确，或调整时间范围</p>
            </div>
          ) : (
            <div className="space-y-4 max-h-96 overflow-y-auto">
              {gitData.map((change, index) => (
                <div key={index} className="border border-gray-200 rounded-lg p-4">
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex items-center">
                      <Hash className="h-4 w-4 text-gray-400 mr-2" />
                      <span className="font-mono text-sm text-gray-600">
                        {change.commit?.hash?.substring(0, 8) || 'N/A'}
                      </span>
                    </div>
                    <div className="flex items-center text-sm text-gray-500">
                      <Calendar className="h-4 w-4 mr-1" />
                      {formatDate(change.commit?.date)}
                    </div>
                  </div>
                  
                  <div className="mb-2">
                    <div className="flex items-center mb-1">
                      <User className="h-4 w-4 text-gray-400 mr-2" />
                      <span className="text-sm font-medium text-gray-700">
                        {change.commit?.author || '未知作者'}
                      </span>
                    </div>
                    <p className="text-sm text-gray-900 font-medium">
                      {change.commit?.message || '无提交信息'}
                    </p>
                  </div>

                  <div className="text-sm">
                    <p className="text-gray-600 mb-1">
                      <strong>文件路径:</strong> {change.file}
                    </p>
                    <p className="text-gray-600 mb-1">
                      <strong>变更类型:</strong> 
                      <span className={`ml-1 px-2 py-1 rounded text-xs ${
                        change.type === 'added' ? 'bg-green-100 text-green-800' :
                        change.type === 'modified' ? 'bg-blue-100 text-blue-800' :
                        change.type === 'deleted' ? 'bg-red-100 text-red-800' :
                        'bg-gray-100 text-gray-800'
                      }`}>
                        {change.type === 'added' ? '新增' :
                         change.type === 'modified' ? '修改' :
                         change.type === 'deleted' ? '删除' : change.type}
                      </span>
                    </p>
                    {change.additions !== undefined && (
                      <p className="text-gray-600 mb-1">
                        <strong>变更统计:</strong> 
                        <span className="text-green-600">+{change.additions}</span>
                        {change.deletions !== undefined && (
                          <span className="text-red-600 ml-2">-{change.deletions}</span>
                        )}
                      </p>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Git状态诊断 */}
      {gitStatus && (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="flex items-center mb-4">
            {gitStatus.isRepoValid ? (
              <CheckCircle className="h-5 w-5 text-green-600 mr-2" />
            ) : (
              <AlertCircle className="h-5 w-5 text-red-600 mr-2" />
            )}
            <h3 className="text-lg font-semibold text-gray-900">
              Git仓库诊断信息
            </h3>
          </div>

          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  仓库状态
                </label>
                <div className={`px-3 py-2 rounded-md text-sm ${
                  gitStatus.isRepoValid 
                    ? 'bg-green-100 text-green-800' 
                    : 'bg-red-100 text-red-800'
                }`}>
                  {gitStatus.isRepoValid ? '✓ 有效的Git仓库' : '✗ 无效的Git仓库'}
                </div>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  提交记录数量
                </label>
                <div className="px-3 py-2 bg-blue-100 text-blue-800 rounded-md text-sm">
                  {gitStatus.totalCommits || 0} 条提交记录
                </div>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                仓库路径
              </label>
              <div className="px-3 py-2 bg-gray-100 text-gray-800 rounded-md text-sm font-mono">
                {gitStatus.repoPath}
              </div>
            </div>

            {gitStatus.errorMessage && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  错误信息
                </label>
                <div className="px-3 py-2 bg-red-100 text-red-800 rounded-md text-sm">
                  {gitStatus.errorMessage}
                </div>
              </div>
            )}

            {gitStatus.rawLogContent && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  原始Git日志内容 (前500字符)
                </label>
                <div className="px-3 py-2 bg-gray-100 text-gray-800 rounded-md text-sm font-mono max-h-32 overflow-y-auto">
                  {gitStatus.rawLogContent.substring(0, 500)}
                  {gitStatus.rawLogContent.length > 500 && '...'}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* 所有Git提交记录 */}
      {allCommits && showAllCommits && (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center">
              <Database className="h-5 w-5 text-blue-600 mr-2" />
              <h3 className="text-lg font-semibold text-gray-900">
                所有Git提交记录 ({filteredCommits.length}/{allCommits.length} 条)
              </h3>
            </div>
            <button
              onClick={exportDebugData}
              className="flex items-center px-4 py-2 bg-gradient-to-r from-neutral-600 to-neutral-700 text-white rounded-xl hover:from-neutral-700 hover:to-neutral-800 focus:outline-none focus:ring-2 focus:ring-neutral-500 focus:ring-offset-2 transition-all duration-300 font-medium shadow-medium hover:shadow-strong transform hover:scale-105"
            >
              <Download className="h-4 w-4 mr-2" />
              <span>导出数据</span>
            </button>
          </div>

          {/* 筛选控件 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                搜索提交信息/Hash
              </label>
              <input
                type="text"
                value={commitFilter}
                onChange={(e) => setCommitFilter(e.target.value)}
                placeholder="输入关键词搜索..."
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                筛选作者
              </label>
              <select
                value={authorFilter}
                onChange={(e) => setAuthorFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
              >
                <option value="">所有作者</option>
                {getUniqueAuthors().map(author => (
                  <option key={author} value={author}>{author}</option>
                ))}
              </select>
            </div>
            
            <div className="flex items-end">
              <button
                onClick={() => {
                  setCommitFilter('');
                  setAuthorFilter('');
                }}
                className="px-4 py-2 bg-gradient-to-r from-neutral-500 to-neutral-600 text-white rounded-xl hover:from-neutral-600 hover:to-neutral-700 focus:outline-none focus:ring-2 focus:ring-neutral-500 focus:ring-offset-2 transition-all duration-300 font-medium shadow-medium hover:shadow-strong transform hover:scale-105"
              >
                <span>清除筛选</span>
              </button>
            </div>
          </div>

          {/* 提交记录表格 */}
          {filteredCommits.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              <Database className="h-12 w-12 text-gray-300 mx-auto mb-4" />
              <p>没有找到匹配的提交记录</p>
              <p className="text-sm mt-2">请调整筛选条件或检查Git仓库</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Hash
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      作者
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      日期
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      提交信息
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {filteredCommits.map((commit, index) => (
                    <tr key={commit.hash || index} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-mono text-gray-900">
                        {commit.hash.substring(0, 8)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {commit.author}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {formatDate(commit.date)}
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-900">
                        <div className="max-w-xs truncate" title={commit.message}>
                          {commit.message}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}
    </div>
  );
};